import React, { Component } from 'react';
import styled from 'styled-components';

import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import AnswerItem from 'component/Lists/AnswerList/AnswerItem';
import ContainerWithBottomLine from 'widget/ContainerWithBottomLine';
import { URL } from 'service/URLService';
import RestService from 'service/RequestServices/RestService';
import EmptyPage from 'widget/EmptyPage';
import Loading from 'widget/Loading';
import Time from 'util/Time';
import CommentList from 'component/Lists/CommentList';
import More from '../More';

const Root = styled.div`
  position: relative;
  min-height: 100px;
`;

const ListContainer = styled(ContainerWithBottomLine)`
  padding: 16px 20px;
`;

class AnswerList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      list: props.data.list,
      total: props.data.total
    };
    this.handleClickMore = this.handleClickMore.bind(this);
  }

  fetchData(offset) {
    const { id, from } = this.props;
    const limit = 10;

    const Method = {
      index: (_, _limit, _offset) => RestService.fetchRestList('answers', _limit, _offset),
      question: (_id, _limit, _offset) =>
        RestService.fetchRestList(
          'answers',
          _limit,
          _offset,
          `questionID=${_id}&order=supporters_counts`
        ),
      profile: (_id, _limit, _offset) =>
        RestService.fetchRestList('answers', _limit, _offset, `answerProfileID=${_id}`)
    }[from];

    Method(id, limit, offset)
      .then(message => {
        const list = message;
        this.state.loading = false;
        this.state.list = this.state.list.concat(list);
        this.setState(this.state);
      })
      .catch(err => {
        console.warn(err);
      });
  }

  fetchMore() {
    const { list } = this.state;
    const offset = list.length;
    this.fetchData(offset);
  }

  handleClickMore() {
    this.state.loading = true;
    this.fetchMore();
    this.setState(this.state);
  }

  render() {
    const { data, expand, from, ...props } = this.props;
    const { loading, list, total } = this.state;

    const more = total - list.length;
    const hasMore = more > 0;

    return (
      <Root {...props} style={{ minHeight: list.length === 0 && 180 }}>
        {list.length === 0 && (
          <EmptyPage>
            <FormattedMessage id="nodata.answer" />
          </EmptyPage>
        )}
        <FormattedMessage id="list.answer.at">
          {([txt]) =>
            list.map((item, index) => {
              return (
                <ListContainer key={item.id} bottomLine={index < total - 1}>
                  <AnswerItem
                    expand={expand}
                    data={{
                      id: item.id,
                      title: from === 'question' ? null : item.question.title,
                      link: URL.question(item.questionID),
                      profile: {
                        ...item.answerProfile,
                        desc: `${txt} ${Time(item.updateAt)}`
                      },
                      content: item.content,
                      social: {
                        supported: item.supported,
                        supportersCounts: item.supportersCounts,
                        commentsCounts: item.commentsCounts
                      }
                    }}
                    injectComponent={attr => (
                      <CommentList {...attr} id={item.id} total={item.commentsCounts} />
                    )}
                  />
                </ListContainer>
              );
            })
          }
        </FormattedMessage>
        {hasMore && (
          <ListContainer key="more">
            {!loading && (
              <More onClick={this.handleClickMore}>
                <FormattedMessage id="list.answer.more" />({more})
              </More>
            )}
            {loading && <Loading />}
          </ListContainer>
        )}
      </Root>
    );
  }
}

AnswerList.defaultProps = {
  expand: false
};

AnswerList.propTypes = {
  id: PropTypes.number.isRequired,
  from: PropTypes.string.isRequired,
  data: PropTypes.shape({
    total: PropTypes.number.isRequired,
    list: PropTypes.arrayOf(
      PropTypes.shape({
        id: PropTypes.number.isRequired
      })
    ).isRequired
  }).isRequired,
  expand: PropTypes.bool
};

export default AnswerList;
